#include <QSqlDatabase>
#include <QMessageBox>
#include <QDir>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

#include "login.h"
#include "ui_login.h"
#include "reg_page.h"
#include "data_handle.h"
#include "sql_handle.h"

user_info_t user_info = {"null"};

login::login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::login)
{
    ui->setupUi(this);
}

login::~login()
{
    delete ui;
}

void login::on_pushButton_clicked()
{
    reg_page *r = new reg_page; // 使用指针和 new 关键字来保持窗口在堆上存活
    r->show();
    this->close();
}

void login::on_pushButton_2_clicked()
{
    QCoreApplication::exit();
}

void login::on_login_Button_clicked()
{
    QString username = ui->user_Edit->text();
    QString password = ui->password_Edit->text();

#if 1
    sql_handle data;
    QSqlDatabase db = data.db;
    QSqlQuery query(db);

#elif 0
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("example.db");

    if (!db.open()) {
        QMessageBox::information(this, "infor", "连接失败");
        return;
    }

    QString createTableQuery = R"(
        CREATE TABLE IF NOT EXISTS SWIFTCHEN (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT NOT NULL,
            password TEXT NOT NULL,
            sales_amount INTEGER DEFAULT 0
        )
    )";

    QSqlQuery query(db);
    if (!query.exec(createTableQuery)) {
        QMessageBox::information(this, "infor", "创建表失败");
        return;
    }

    if (!db.open()) {
        QMessageBox::critical(this, "数据库错误", "无法连接到数据库: " + db.lastError().text());
        return;
    }
#endif

    query.prepare("SELECT * FROM SWIFTCHEN WHERE username = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    if (query.exec())
    {
        if (query.next())
        {
            QMessageBox::information(this, "infor","登录成功");
            user_info.user = username.toStdString();
            data_handle *d = new data_handle; // 使用指针和 new 关键字来保持窗口在堆上存活
            d->show();
            this->close(); // 关闭主窗口
        }
        else
        {
            QMessageBox::information(this, "infor","该用户不存在或连接失败");
        }
    }
    else
    {
        QMessageBox::critical(this, "查询错误", "查询失败: " + query.lastError().text());
    }

    return;
}

